﻿using ICSharpCode.AvalonEdit.Editing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using UnifiedTool.Model;

namespace UnifiedTool.UIControl.DiyUserControl
{
    /// <summary>
    /// MusicPlayerControl.xaml 的交互逻辑
    /// </summary>
    public partial class MusicPlayerControl : UserControl
    {

        private Double volum = 0.00;
        private DispatcherTimer? timer = null;
        private int PlayStatus = 0;
        private int selectSong = 0;


        public MusicPlayerControl()
        {
            InitializeComponent();

            volumeSlider.Value = mediaPlayer.Volume * 10;

            SongTitle.Content = "";
            SongAuthor.Content = "";
            
            // 定时器更新 Slider 值
            if (timer == null)
            {
                timer = new DispatcherTimer();
            }

            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += (sender, args) =>
            {
                // 更新播放时间
                TimeSpan postion = mediaPlayer.Position;
                progressTextBlock.Text = postion.ToString(@"m\:ss");
                // 更新播放进度条
                timeSlider.Value = postion.TotalSeconds;

/*                System.Diagnostics.Debug.WriteLine("播放进度：" + postion.TotalSeconds);*/

                if (selectSong != MediaMetadata.SelectId)
                {

                    MusicInfo song = MediaMetadata.getMusic(selectSong = MediaMetadata.SelectId);
                    Uri uri = new Uri(song.Uri);
                    mediaPlayer.Source = uri;

                    SongTitle.Content = song.Title;
                    SongAuthor.Content = song.Artist;
                    if (song.Cover != string.Empty)
                    {
                        BitmapImage image = new BitmapImage();
                        image.BeginInit();  // 初始化BitmapImage
                        image.CacheOption = BitmapCacheOption.OnLoad; // 加载图像到内存中
                        image.UriSource = new Uri(song.Cover);
                        image.EndInit();    // 结束初始化

                        SongImage.Source = image;
                        /*                        System.Diagnostics.Debug.WriteLine("加载封面：" + song.Cover);*/

                        /*                        // 创建一个新的Window
                                                Window imageWindow = new Window();
                                                imageWindow.Title = "封面";
                                                imageWindow.Width = image.PixelWidth;
                                                imageWindow.Height = image.PixelHeight;

                                                // 创建一个新的Image控件
                                                Image imageControl = new Image();
                                                imageControl.Source = image;

                                                // 将Image控件添加到窗口中
                                                imageWindow.Content = imageControl;

                                                // 显示窗口
                                                imageWindow.ShowDialog();*/
                    }

                    if (selectSong == MediaMetadata.SelectId)
                    {
                        if (PlayStatus != 1)
                        {
                            mediaPlayer.Play();
                            PlayStatus = 1;
                            PlayButton.Visibility = Visibility.Hidden;
                            PauseButton.Visibility = Visibility.Visible;
                        }
                    }

                }

            };

            timer.Start();


        }



        private void PlayButton_Click(object sender, RoutedEventArgs e)
        {
            if (selectSong == MediaMetadata.SelectId && selectSong != 0) {
               if (PlayStatus != 1)
               {
                   mediaPlayer.Play();
                   PlayStatus = 1;
                   PlayButton.Visibility = Visibility.Hidden;
                   PauseButton.Visibility = Visibility.Visible;

               }
            }

        }



        private void PauseButton_Click(object sender, RoutedEventArgs e)
        {
            if (PlayStatus != 2) {
                mediaPlayer.Pause();
                PlayStatus = 2;
                PlayButton.Visibility = Visibility.Visible;
                PauseButton.Visibility = Visibility.Hidden;
            }

        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            if (PlayStatus != 0) {
                timeSlider.Value = 0;
                mediaPlayer.Stop();
                PlayStatus = 0;
            }

        }

        private void MuteButton_Click(object sender, RoutedEventArgs e)
        {
            mediaPlayer.IsMuted = !mediaPlayer.IsMuted;
            if (mediaPlayer.IsMuted)
            {
                volum = volumeSlider.Value / 10;
                VolumeIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.VolumeMute;
                volumeSlider.Value = 0;

            }
            else {
                if (volum <= 0)
                {
                    volumeSlider.Value = (volum + 0.5) * 10;
                }
                volumeSlider.Value = volum * 10;
                VolumeIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.VolumeSource;

            }
            
        }

        #region 手动调整滑块执行的方法
        private void timeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (mediaPlayer.NaturalDuration.HasTimeSpan)
            {
                var position = TimeSpan.FromSeconds(timeSlider.Value);
                mediaPlayer.Position = position;
                // 根据进度条更新进度时间
                progressTextBlock.Text = mediaPlayer.Position.ToString(@"m\:ss");
            }
        }
        #endregion
        private void volumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (volumeSlider.Value <= 0)
            {
                mediaPlayer.IsMuted = true;
                VolumeIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.VolumeMute;
            }
            else {
                mediaPlayer.IsMuted = false;
                VolumeIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.VolumeSource;
            }
            double volumes = volumeSlider.Value / 10;
            mediaPlayer.Volume = volumes;
        }

        private void mediaPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            timeSlider.Maximum = mediaPlayer.NaturalDuration.TimeSpan.TotalSeconds;
            // 获取音频文件的总时长
            TimeSpan span = mediaPlayer.NaturalDuration.TimeSpan;
            durationTextBlock.Text = span.ToString(@"m\:ss");

        }

        private void mediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            mediaPlayer.Stop();
            timeSlider.Value = 0;
            PlayStatus = 0;
            PlayButton.Visibility = Visibility.Visible;
            PauseButton.Visibility = Visibility.Hidden;
            // 音频播放结束后重置进度条
            progressTextBlock.Text = "0:00";
            //上一首播放完成，进行下一首播放
            string message = "已经最后一个了";
            List<MusicInfo> musicInfos = MediaMetadata.getMusicItems();
            for (int i = 0; i < musicInfos.Count; i++)
            {
                MusicInfo currentItem = musicInfos[i];
                MusicInfo nextItem = null;
                if ((i + 1) <= (musicInfos.Count -1)) {
                    nextItem = musicInfos[i + 1];
                }

                if (nextItem != null)
                {
                    if (currentItem != null)
                    {
                        if (currentItem.Id == selectSong)
                        {
                            MediaMetadata.SelectId = nextItem.Id;
                            message = "切换下一首：" + nextItem.Title;
                            break;
                        }
                    }
                }
            }
            System.Diagnostics.Debug.WriteLine(message);

        }
    }
}
